package com.itany.controller;

import com.github.pagehelper.PageInfo;
import com.itany.entity.Loop;
import com.itany.entity.ManagerUser;
import com.itany.service.LoopService;
import com.itany.utils.SFTPUtils;
import com.itany.vo.ResponseResult;
import com.itany.vo.UeditorResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Author:yaozhiyuan0117@163.com
 * Time:2019/12/20 19:34
 * Describe:
 * version:1.0
 */

@RestController
@RequestMapping("/loop")
public class LoopController {

    @PostMapping("/findByPage")
    public Map findByPage(Integer page, Integer rows){
        PageInfo<Loop> pageInfo = loopService.findByPage(page,rows);
        Map map = new HashMap();
        map.put("total", pageInfo.getTotal());
        map.put("rows",pageInfo.getList());
        System.out.println(pageInfo.getList());
        return map;
    }

    @Autowired
    LoopService loopService;
    @RequestMapping("/addloop")
    public Map addLoop(String content, Integer articleId, MultipartFile file, HttpServletRequest request) throws Exception {

        // 1.上传图片到SFTP服务器
        String fileName = file.getOriginalFilename();
        fileName=System.currentTimeMillis()+fileName.substring(fileName.lastIndexOf("."));

        System.out.println("-------------");
        System.out.println("fileName "+ fileName);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String  uploadDir ="yzy/" +dateFormat.format(new Date())+"/";

        SFTPUtils.sftpPut("192.168.4.8","tyh","123",22,uploadDir,file.getInputStream(),fileName);

        // 2.获取上传路径
        String imgurl = uploadDir + fileName;
        System.out.println("imgurl "+ imgurl);
        Loop loop = new Loop();
        loop.setArticleId(articleId);
        loop.setImgurl(imgurl);
        loop.setStatus(1);
        loop.setContent(content);

        loopService.addLoop(loop);
        Map map = new HashMap();
        return map;

    }

    @PostMapping("/modifyStatus")
    public ResponseResult modifyStatus(Integer id, Integer flag){
        Loop loop = new Loop();
        loop.setId(id);
        loop.setStatus(flag);
        loopService.modifyStatus(loop);
        return ResponseResult.success();
    }

    @PostMapping("/delete")
    // fileName暂时没有用到，应该是用来删除fstp远程的文件
    public ResponseResult delete(Integer id, String fileName){
        loopService.delete(id);
        return ResponseResult.success();

    }

}
